package com.xtt.dynamic.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;

import javax.sql.DataSource;

@Configuration
//集成mybatis
//1、指定扫描的mapper接口包(从库)
//2、指定使用SqlSessionFactory是哪个(从库)
@MapperScan(basePackages = "com.xtt.dynamic.mapper.r",
        sqlSessionFactoryRef = "readSqlSessionFactory"
)
public class ReadMybatisConfig {
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.datasource2")
    public DataSource dataSource2(){
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public SqlSessionFactory readSqlSessionFactory() throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        //指定从库
        sessionFactory.setDataSource(dataSource2());
        //指定主库对应的mapper.xml文件
//        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
//                .getResource("classpath:mapper/r/*.xml"));
        //主库设置sql控制台打印
//        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
//        configuration.setLogImpl(StdOutImpl.class);
//        sessionFactory.setConfiguration(configuration);
        return sessionFactory.getObject();
    }

    //配置从库事务管理器
    @Bean
    public DataSourceTransactionManager rTransactionManager(){
        DataSourceTransactionManager dataSourceTransactionManager=new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource2());
        return dataSourceTransactionManager;
    }

    @Bean
    public TransactionTemplate rTransactionTemplate(){
       return new TransactionTemplate(rTransactionManager());
    }
}
